<?php
namespace app\middleware;

use app\admin\Auth;
use app\model\AdminModel;
use Shopwwi\LaravelCache\Cache;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class Admin implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {

        $controller = $request->controller;
        $action = $request->action;
        $app = $request->app;

        if ($controller != 'app\admin\controller\PublicController') {

            //验证管理员是否登录
            $token = $request->header('ADMIN-TOKEN');
            
            $adminid = Cache::tags('admin')->get('token_'.$token);

            if(empty($token) || empty($adminid)){
                return error("请先登录",[],[],10001);
            }

            //查询管理员
            $admin = AdminModel::find($adminid);

            if(empty($admin)){
                return error("请重新登录",[],[],10001);
            }

            //权限验证
            if (!Auth::canAccess($adminid, $controller, $action, $app)) {
                return error('没有访问权限!');
            }

            $request->admin = $admin;
            $request->adminid = $adminid;
            $request->token = $token;
        }

        return $handler($request);
    }
    
}
